package kr.pe.dothome.yyar.myphone;

import kr.pe.dothome.yyar.myphone.controller.MissedMessageSendingTask;
import kr.pe.dothome.yyar.myphone.controller.Responser;
import kr.pe.dothome.yyar.myphone.domain.Request;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

import android.util.Log;

import android.view.View;
import android.widget.Toast;


public class GetMissedMyphoneInformationActivity extends Activity {
	/** Called when the activity is first created. */
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
//		getRegistrationId();
	}
	
	// TODO deprecated
	public void sendRequestData() {
		Log.d("Registration", "Registration Started");
		String rid = "TESTRID010101010";
		Long startDate = 1334487145L;
		
		Responser resp = new Responser(this.getContentResolver(), startDate);
		Request req = resp.getRequestResponse(rid);
		
		new MissedMessageSendingTask(getBaseContext()).execute(req);
		
		Log.d("requestMessages", req.toString());	
	}
	
	public void registerC2DM(final View view) {
		
		Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
		registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
		registrationIntent.putExtra("sender", "yymjar@gmail.com");
		startService(registrationIntent);		
		
		Toast.makeText(getBaseContext(), "C2DM registration ID requested", Toast.LENGTH_SHORT).show();
	}
	
	public void unregisterC2DM(final View view) {		
		Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
		unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		startService(unregIntent);
		
		SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
		preference.edit().remove("rid").commit();
		
		Toast.makeText(getBaseContext(), "C2DM unregistration completed", Toast.LENGTH_SHORT).show();
	}
	
	private void getRegistrationId() {
		SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
		String registrationId = preference.getString("rid", null);
		preference = null;
		
		if(registrationId == null) {
			Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
			registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
			registrationIntent.putExtra("sender", "yymjar@gmail.com");
			startService(registrationIntent);		
			
			Log.d("Registration", "Registration Started");
		}
		else {
//			this.registrationId = registrationId;
			Log.d("Registration", "Registration Id : " + registrationId + ", Length : " + registrationId.length());
		}
	}

}